import { defineStore } from 'pinia'
import * as video from '@/apis/video'

export interface typeUserInfo {
  avatarUrl?: string
  user?: string
  username?: string
  _id?: string
  token?: string
}
let isFetched = false
export const useUserState = defineStore('userState', {
  state: (): {
    __state: typeUserInfo | null
  } => {
    return {
      __state: null
    }
  },
  getters: {},
  actions: {
    async getUserInfo(): Promise<typeUserInfo | null> {
      if (isFetched || this.__state?.user) return this.__state
      return new Promise<typeUserInfo | null>((resolve, reject) => {
        video.getUserInfo().then(res => {
          if (res.data.code != 200) {
            isFetched = true
            reject(false)
            return
          }
          this.__state = res.data.data
          resolve(this.__state)
        })
      })
    },
    async loginOut() {
      return new Promise<void>((resolve, reject) => {
        video.loginOut().then(res => {
          this.__state = null
          resolve()
        })
      })
    }
  }
})
